# -*- coding: UTF-8 -*-
# Author: Damon(wuud1)
# CreateDate: 
# Message:

import requests
import base64
from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey import RSA
import time
import json
from untils.yun_da_ma import code_verificate
from untils.chaojiying import Chaojiying_Client
from setting import *

class ChanganLogin:

    def __init__(self, username, password):
        self.username = username
        self.password = password
        self.cookies = {}
        self.headers = {}

    def get_loginHtml(self):
        url = "http://epc.changan.com.cn:8080/front/login.html"
        self.headers = {
            "Host": "epc.changan.com.cn:8080",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.96 Safari/537.36",
        }
        response = requests.get(url=url, headers=self.headers)
        with open("./login.html", 'w') as l:
            l.write(response.content.decode())
        cookies = response.cookies.get_dict()
        for k in cookies:
            self.cookies[k] = cookies[k]

    def selectSlideShow(self):
        url = "http://epc.changan.com.cn:8080/system/sys-slide-show/selectSlideShow"
        self.headers = {
            "Host": "epc.changan.com.cn:8080",
            "Accept": "application/json, text/javascript, */*; q=0.01",
            "Origin": "http://epc.changan.com.cn:8080",
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.96 Safari/537.36",
            "Referer": "http://epc.changan.com.cn:8080/front/login.html",
            "Content-Type": "application/x-www-form-urlencoded",
        }
        data = {}
        response = requests.post(url=url, headers=self.headers, cookies=self.cookies, data=data)
        print(response.content.decode())
        cookies = response.cookies.get_dict()
        for k in cookies:
            self.cookies[k] = cookies[k]

    def get_verifyCode(self):
        self.headers = {
            "Host": "epc.changan.com.cn:8080",
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.96 Safari/537.36",
            "Accept": "image/webp,image/apng,image/*,*/*;q=0.8",
            "Referer": "http://epc.changan.com.cn:8080/front/login.html",
        }
        self.identifyingId = str(time.time()).replace('.', '')
        url = "http://epc.changan.com.cn:8080/kaptcha/identifyingCode?identifyingId={}".format(self.identifyingId)
        response = requests.get(url=url, headers=self.headers, cookies=self.cookies)
        cookies = response.cookies.get_dict()
        for k in cookies:
            self.cookies[k] = cookies[k]
        with open('./code.png', 'wb') as c:
            c.write(response.content)

    def login_post(self):
        url = "http://epc.changan.com.cn:8080/system/sys-dealer/login"
        self.headers = {
            "Host": "epc.changan.com.cn:8080",
            "Origin": "http://epc.changan.com.cn:8080",
            "X-Requested-With": "XMLHttpRequest",
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.96 Safari/537.36",
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "Referer": "http://epc.changan.com.cn:8080/front/login.html",
        }
        en_user, en_pawd = self.encrypt_(self.username, self.password)
        # rs = code_verificate('./code.png', ydm_username, ydm_password, ydm_appId, ydm_appKey, code_type=1006)
        # verifyCode = rs[0]
        # 超级鹰打码
        chaojiying = Chaojiying_Client('peipeiyun', '1qaz@WSX', '96001')
        im = open('./code.png', 'rb').read()
        valid_obj = chaojiying.PostPic(im, 1902)
        verifyCode = valid_obj['pic_str']
        data = {
            "account": en_user,
            "password": en_pawd,
            "identifyingCode": verifyCode,
            "identifyingId": self.identifyingId,
        }
        response = requests.post(url=url, headers=self.headers, cookies=self.cookies, data=data)
        jsonData = json.loads(response.content.decode())
        # print(response.content.decode())
        # print(jsonData.get("data").get("token"))
        # print(self.cookies.get("JSESSIONID"))
        data = {
            "cookies": self.cookies,
            "token": jsonData.get("data").get("token")
        }
        return data

    def encrypt_(self, username, password, publicKey=None):
        if not publicKey:
            publicKey = '-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCrWhB6f7MQIg51sULk0mQi6WrEv1ZjkbYr0sXp1b2oe8fT3WkkKurYBec05bGKAm02zSB7OBNfs2qVyMgRKUZNmqGvT+wMvQS0lfhXisXYqu+aRWPYatud+Y40aURjdui+sqlFIVLEdvbjLqnEhielTIoCaNULwmgCLdPOjZoJvwIDAQAB\n-----END PUBLIC KEY-----'
        rsakey = RSA.importKey(publicKey)
        cipher = PKCS1_v1_5.new(rsakey)
        encryped_username = base64.b64encode(cipher.encrypt(username.encode()))
        encryped_password = base64.b64encode(cipher.encrypt(password.encode()))
        return [encryped_username, encryped_password]

    def login(self):
        self.get_loginHtml()
        self.selectSlideShow()
        self.get_verifyCode()
        return self.login_post()


if __name__ == '__main__':

    tools = ChanganLogin(ca_username, ca_password)
    tools.login()